<?php

namespace app\admin\controller\dts\plan;

use app\common\controller\Backend;
use think\Db;

/**
 * 教学计划管理
 *
 * @icon fa fa-circle-o
 */
class Teaching extends Backend
{

    /**
     * Teaching模型对象
     * @var \app\admin\model\dts\plan\Teaching
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\dts\plan\Teaching;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function index() {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            
            $query = [];
            $classesArr = Db::name('dts_classes')->whereRaw('monitor_id = '.$this->auth->id . ' OR FIND_IN_SET('.$this->auth->id.', teacher_ids) > 0')->select();
            if($classesArr) {
                $query = ['teaching.classes_id' => ['in', array_column((array)$classesArr, 'id')]];
            }

            $defaultJoin = [
                ['dts_classes classes', 'classes.id = teaching.classes_id', 'left']
            ];

            $list = Db::name('dts_plan_teaching')->alias('teaching')
            ->field('teaching.*,classes.name as classes__name')
            ->join($defaultJoin)
            ->where($where)
            ->where($query)
            ->order($sort, $order)
            ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => paginateList($list));

            return json($result);
        }

        return $this->view->fetch();
    }

    protected function before_edit($params, $changeData, $originData)
    {
        $arr = ['#FF9F0E', '#FF576B', '#9757FF', '#41CC58'];
        foreach($params['content'] as $key1 => $item1) {
            foreach($item1['list'] as $key2 => $item2) {
                if($item2['label'] || $item2['target'] || $item2['focus'] || $item2['remark']) {
                    $params['content'][$key1]['list'][$key2]['color'] = $item2['color'] ? $item2['color'] :  $arr[rand(0, count($arr) - 1)];
                }
            }
        }
        $params['content'] = json_encode($params['content']);
        return $params;
    }

    //详情
    public function details($ids = null) {

        $row = $this->model->where('id', $ids)->find();

        $this->assign('row', $row);
        return $this->view->fetch();
    }
}
